import { FC, useState, useEffect } from 'react';
import ApiCollector from '@/const/apis';
// import useListPages from '@/hooks/useListPages';
import FetchTips from '@/components/fetchTips';
import Layout from '@/components/layout';
import ListLoader from '@/components/skeleton/listLoader';
import Lines from '@/components/echarts';
import EchartsPie from '@/components/echartsPie';
import EchartsBar from '@/components/echartsBar';
import ContentEcharts from '@/components/contentEcharts';
import styles from './index.module.less';
import Card from '@/components/card';
import ComNavBar from '@/components/comNavBar';
import { Tabs, Progress } from '@nutui/nutui-react';
import { routesUrl } from '@/const/routes';
import { useNavigate } from 'react-router';
import useMockRequest from '@/hooks/useMockRequest';
import big from '@/images/big.png';
import small from '@/images/small.png';
import magicStore from '@/store/magic';
import { observer } from 'mobx-react-lite'
// import { get } from 'mobx';
import get from 'lodash/get';
import { returnFloat } from '@/utils/tool';

const style = {
    '--nutui-tabs-titles-item-active-color': "rgb(0, 145, 255)",
    "--nutui-tabs-titles-background-color": "#fff",
    "--nutui-tabs-horizontal-tab-line-color": "#0091FF",
    "--nutui-tabs-titles-item-color": "rgba(0, 0, 0, 0.5)",
    "--nutui-tabs-titles-item-active-font-weight": 500,
    "--nutui-tabs-tab-line-color": "#0091FF",
    "--nutui-tabs-tab-line-width":"28px"
}
const grid = {
    top: "20%",
    bottom: '10%',
    left: '1%',
    right: '8%',
}

const gridFull = {
    top: "8%",
    bottom: '10%',
    left: '6%',
    right: '10%',
}

const SystemList = () => {
    const navigate = useNavigate();
    // const { loading, list, ifDone } = useListPages(ApiCollector.getSysList, {});  后期分页
    const [tab4value, setTab4value] = useState(0);
    const [apiListData, setApiListData] = useState({});
    const [fullScreenOpenOrClose, setFullScreenOpenOrClose] = useState(false)
    const [fullScreenType, setFullScreenType] = useState('')
    const [fullScreenTitle, setFullScreenTitle] = useState('')
    const [fullScreenValue, setFullScreenValue] = useState({})
    const tabTitle = ["WAF应用防火墙", "安全态势感知", "服务器安全防护"]
  
    const getBmdfxs = useMockRequest(ApiCollector.getBmdfxs, {
        config: { 
            ready: tab4value == 0 ? true : false,
            onSuccess:(res,params)=>{
                let value1 = get(res.data,'result',{})
                setApiListData({
                    value1: {
                        xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                        lineData: [{
                            name: '本周',
                            value: get(value1, 'valuesThisWeek', []),
                        },
                        {
                            name: '上周',
                            value: get(value1, 'valuesPreWeek', []),
                        }]
                    }
                })
            }
         }
    });
    const {run:getBmdfxlx,data:getBmdfxlxData} = useMockRequest(ApiCollector.getBmdfxlx, {
        config: { 
            ready: tab4value == 0 ? true : false , 
            manual:true,
            onSuccess:(res,params)=>{
                console.log(res,'res')
                let value2 = get(res.data,'result',{})
                if (value2 && value2.length) {
                    value2 = value2.map(item => {
                        return {
                            name: item.EVENT_TYPE,
                            value: item.event_count
                        }
                    })
                }
                setApiListData((pre)=>({
                    ...pre,
                    value2
                }))
            }
        }
    });
    const {run:getBmdfxxtJr,data:getBmdfxxtJrData} = useMockRequest(ApiCollector.getBmdfxxtJr, {
        config: { 
            ready: tab4value == 0 ? true : false, 
            manual:true,
            onSuccess:(res,params)=>{
                let value3 = get(res.data,'result',{})
                
                setApiListData((pre)=>({
                    ...pre,
                    value3
                }))
            }
        }
    });
    const getGjcgs = useMockRequest(ApiCollector.getGjcgs, {
        config: { 
            ready: tab4value == 1 ? true : false,
            onSuccess:(res,params)=>{
                let value4 = get(res.data,'result',{})
                setApiListData((pre)=>({
                    ...pre,
                    value4: {
                        xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                        lineData: [{
                            name: '本周',
                            value: get(value4, 'valuesThisWeek', []),
                        },
                        {
                            name: '上周',
                            value: get(value4, 'valuesPreWeek', []),
                        }]
                    }
                }))
            }
         }
    });
    const {run:getGjsbs,data:getGjsbsData} = useMockRequest(ApiCollector.getGjsbs, {
        config: { 
            ready: tab4value == 1 ? true : false , 
            manual:true,
            onSuccess:(res,params)=>{
                let value5 = get(res.data,'result',{})
                setApiListData((pre)=>({
                    ...pre,
                    value5: {
                        xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                        lineData: [{
                            name: '本周',
                            value: get(value5, 'valuesThisWeek', []),
                        },
                        {
                            name: '上周',
                            value: get(value5, 'valuesPreWeek', []),
                        }]
                    },
                }))
            }
        }
    });
    const {run:getGjcgflzb,data:getGjcgflzbData} = useMockRequest(ApiCollector.getGjcgflzb, {
        config: { 
            ready: tab4value == 1 ? true : false , 
            manual:true,
            onSuccess:(res,params)=>{
                let value6 = get(res.data,'result',{})
                if (value6 && value6.length) {
                    value6 = value6.map(item => {
                        return {
                            name: item.module_name,
                            value: item.total_count
                        }
                    })
                }
                setApiListData((pre)=>({
                    ...pre,
                    value6
                }))
            }
        }
    });
    const getFhqsjljl = useMockRequest(ApiCollector.getFhqsjljl, {
        config: { 
            ready: tab4value == 2 ? true : false,
            onSuccess:(res,params)=>{
                let value7 = get(res.data,'result',{})
                setApiListData((pre)=>({
                    ...pre,
                    value7: {
                        xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                        lineData: [{
                            name: '本周',
                            value: get(value7, 'valuesThisWeek', []),
                        },
                        {
                            name: '上周',
                            value: get(value7, 'valuesPreWeek', []),
                        }]
                    },
                }))
            }
        }
    });
    const {run:getIpssjljl,data:getIpssjljlData} = useMockRequest(ApiCollector.getIpssjljl, {
        config: { 
            ready: tab4value == 2 ? true : false ,
            manual:true,
            onSuccess:(res,params)=>{
                let value8 = get(res.data,'result',{})
                setApiListData((pre)=>({
                    ...pre,
                    value8: {
                        xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                        lineData: [{
                            name: '本周',
                            value: get(value8, 'valuesThisWeek', []),
                        },
                        {
                            name: '上周',
                            value: get(value8, 'valuesPreWeek', []),
                        }]
                    },
                }))
            }
        }
    });
    const {run:getEyrjsjcll,data:getEyrjsjcllData} = useMockRequest(ApiCollector.getEyrjsjcll, {
        config: { 
            ready: tab4value == 2 ? true : false , 
            manual:true,
            onSuccess:(res,params)=>{
                let value9 = get(res.data,'result',{})
                setApiListData((pre)=>({
                    ...pre,
                    value9: {
                        xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                        lineData: [{
                            name: '本周',
                            value: get(value9, 'valuesThisWeek', []),
                        },
                        {
                            name: '上周',
                            value: get(value9, 'valuesPreWeek', []),
                        }]
                    },
                }))
            }
        }
    });
    const {run:getFlrrjljs,data:getFlrrjljsData} = useMockRequest(ApiCollector.getFlrrjljs, {
        config: { 
            ready: tab4value == 2 ? true : false , 
            manual:true,
            onSuccess:(res,params)=>{
                let value10 = get(res.data,'result',{})
                setApiListData((pre)=>({
                    ...pre,
                    value10: {
                        xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                        lineData: [{
                            name: Object.keys(value10).filter(Boolean)[0],
                            value: value10[Object.keys(value10).filter(Boolean)[0]],
                        },
                        {
                            name: Object.keys(value10).filter(Boolean)[1],
                            value: value10[Object.keys(value10).filter(Boolean)[1]],
                        }]
                    },
                }))
            }
        }
    });
    
    useEffect(() => {
        setTab4value(magicStore.magicText)
    }, [magicStore.magicText])

    useEffect(() => {
        let timer = null;
        let timer2 = null;
        if (tab4value == 0) {
            timer = setTimeout(() => {
                getBmdfxlx()
            }, 100);
            timer2 = setTimeout(() => {
                getBmdfxxtJr()
            }, 200);
        }
        return () => clearTimeout(timer, timer2); //清除延时器
    }, [tab4value])

    useEffect(() => {
        let timer = null
        let timer2 = null
        if (tab4value == 1) {
            timer = setTimeout(() => {
                getGjsbs()
            }, 100);
            timer2 = setTimeout(() => {
                getGjcgflzb()
            }, 200);
        }
        return () => clearTimeout(timer, timer2); //清除延时器 

    }, [tab4value])
    
    useEffect(() => {
        let timer = null;
        let timer2 = null;
        let timer3 = null;
        if (tab4value == 2) {
            timer = setTimeout(() => {
                getIpssjljl()
            }, 100);
            timer2 = setTimeout(() => {
                getEyrjsjcll()
            }, 200);
            timer3 = setTimeout(() => {
                getFlrrjljs()
            }, 300);
        }
        return () => clearTimeout(timer, timer2,timer3); //清除延时器


    }, [tab4value])

    const onClickFull = (title, type,value) => {
        setFullScreenOpenOrClose(true)
        setFullScreenType(type)
        setFullScreenTitle(title)
        setFullScreenValue(value)
    }

    const onClickFullClose = () => {
        setFullScreenOpenOrClose(false)
    }

    const firewall = () => {
        console.log(apiListData,'apiListData111')
        return <div className={styles.firewall}>
            <div className={styles.firewall_title}>白名单放行数</div>
            <div className={styles.firewall_echarts}>
                <div className={styles.firewall_echarts_top}>
                    <div className={styles.firewall_echarts_top_img} onClick={() => { onClickFull('放行率', 'line',apiListData?.value1) }}><img src={big} style={{ width: "100%", height: "100%" }} /></div>
                </div>
                {apiListData?.value1 && <Lines xAxisInterval={0} data={apiListData.value1} grid={grid} yAxisPosition={'left'} yAxisAxisLabelFormatter={(value) => {
                    return `${value}`
                }} />}
            </div>
            <div className={styles.firewall_title}>白名单放行类型（TOP10）</div>
            <div className={styles.firewall_echartsPie}>
                {apiListData?.value2 && <EchartsPie data={apiListData.value2} grid={grid} />}
            </div>
            <div className={styles.firewall_title}>白名单放行系统(TOP10)</div>
            <div className={styles.firewall_sysTop}>
                <div className={styles.sysTop_title}>
                    <div className={styles.sysTop_title_name}>系统名称</div>
                    <div className={styles.sysTop_title_value}>当日放行请求数(次)</div>
                    <div className={styles.sysTop_title_per}>放行请求占比</div>
                </div>
                <div className={styles.sysTop_list}>
                    {
                        (apiListData?.value3 || []).map((item, index) => (
                            <div className={styles.sysTop_list_item} key={index}>
                                <div className={styles.list_item_name}>{get(item, 'SERVER', '')}</div>
                                <div className={styles.list_item_value}>{get(item, 'record_count', '')}</div>
                                <div className={styles.list_item_per}>
                                    <div className={styles.list_item_per_gress}>
                                        <Progress
                                            percent={returnFloat(get(item, 'record_ratio', '') * 100)}
                                            color="linear-gradient(270deg, rgba(18,126,255,1) 0%,rgba(32,147,255,1) 32.815625%,rgba(13,242,204,1) 100%)"
                                            animated
                                            strokeWidth="10"
                                        />
                                    </div>
                                    <div className={styles.list_item_per_value}>{returnFloat(get(item, 'record_ratio', '') * 100)}%</div>
                                </div>
                            </div>
                        ))
                    }
                </div>
            </div>
        </div>
    }

    const dyPercep = () => {
        console.log(apiListData,'apiListData222')
        return <div className={styles.firewall}>
            <div className={styles.firewall_title}>攻击成功数</div>
            <div className={styles.firewall_echarts}>
                <div className={styles.firewall_echarts_top}>
                    <div className={styles.firewall_echarts_top_img} onClick={() => { onClickFull('攻击成功数', 'line',apiListData?.value4) }}><img src={big} style={{ width: "100%", height: "100%" }} /></div>
                </div>
                {apiListData?.value4 && <Lines data={apiListData?.value4} xAxisInterval={0} grid={grid} yAxisPosition={'left'} yAxisAxisLabelFormatter={(value) => {
                    return `${value}`
                }} />}
            </div>
            <div className={styles.firewall_title}>攻击失败数</div>
            <div className={styles.firewall_echarts}>
                <div className={styles.firewall_echarts_top}>
                    <div className={styles.firewall_echarts_top_img} onClick={() => { onClickFull('攻击失败数', 'line',apiListData?.value5) }}><img src={big} style={{ width: "100%", height: "100%" }} /></div>
                </div>
                {apiListData?.value5 && <Lines data={apiListData?.value5} xAxisInterval={0} grid={grid} yAxisPosition={'left'} yAxisAxisLabelFormatter={(value) => {
                    return `${value}`
                }} />}
            </div>
            <div className={styles.firewall_title}>攻击成功分类占比(今日数据)</div>
            <div className={styles.firewall_echartsPie}>
                {apiListData?.value6 && <EchartsPie data={apiListData?.value6} grid={grid} />}
            </div>
        </div>
    }

    const safetyProtection = () => {
        console.log(apiListData,'apiListData333')
        return <div className={styles.firewall}>
            <div className={styles.firewall_title}>防火墙事件拦截率</div>
            <div className={styles.firewall_echarts}>
                <div className={styles.firewall_echarts_top}>
                    <div className={styles.firewall_echarts_top_img} onClick={() => { onClickFull('防火墙事件拦截率', 'line' ,apiListData?.value7) }}><img src={big} style={{ width: "100%", height: "100%" }} /></div>
                </div>
                {apiListData?.value7 && <Lines unit='%' part = {true} data={apiListData?.value7} xAxisInterval={0} grid={grid} yAxisPosition={'left'} yAxisAxisLabelFormatter={(value) => {
                    return `${value}%`
                }} />}
            </div>
            <div className={styles.firewall_title}>IPS事件拦截率</div>
            <div className={styles.firewall_echarts}>
                <div className={styles.firewall_echarts_top}>
                    <div className={styles.firewall_echarts_top_img} onClick={() => { onClickFull('IPS事件拦截率', 'line',apiListData?.value8) }}><img src={big} style={{ width: "100%", height: "100%" }} /></div>
                </div>
                {apiListData?.value8 && <Lines unit='%' part = {true} data={apiListData?.value8} xAxisInterval={0} grid={grid} yAxisPosition={'left'} yAxisAxisLabelFormatter={(value) => {
                    return `${value}%`
                }} />}
            </div>
            <div className={styles.firewall_title}>恶意软件事件处理率</div>
            <div className={styles.firewall_echarts}>
                <div className={styles.firewall_echarts_top}>
                    <div className={styles.firewall_echarts_top_img} onClick={() => { onClickFull('恶意软件事件处理率', 'line',apiListData?.value9) }}><img src={big} style={{ width: "100%", height: "100%" }} /></div>
                </div>
                {apiListData?.value9 && <Lines unit='%' part = {true} data={apiListData?.value9 } xAxisInterval={0} grid={grid} yAxisPosition={'left'} yAxisAxisLabelFormatter={(value) => {
                    return `${value}%`
                }} />}
            </div>
            <div className={styles.firewall_title}>防勒索软件拦截数(最近7日)</div>
            <div className={styles.firewall_echarts}>
                <div className={styles.firewall_echarts_top}>
                    <div className={styles.firewall_echarts_top_img} onClick={() => { onClickFull('防勒索软件拦截数(最近7日)', 'bar',apiListData?.value10) }}><img src={big} style={{ width: "100%", height: "100%" }} /></div>
                </div>
                {apiListData?.value10 && <EchartsBar data={apiListData?.value10} grid={grid} yAxisPosition={'left'} yAxisAxisLabelFormatter={(value) => {
                    return `${value}`
                }} />}
            </div>
        </div>
    }

    // console.log(magicStore.magicText,'magicStore.magicText')
    // 如果请求还在加载，则渲染骨架屏
    if (magicStore.magicText === '') return <ListLoader />;
    // console.log(magicStore.magicText,'magicStore.magicText')

    return <Layout title='陕汽核心系统移动端监控' navbar={true}>
        {fullScreenOpenOrClose ? <div className={styles.fullScreen}>
            <div className={styles.sysResponseTime_top}>
                <div className={styles.sysResponseTime_top_left}>{fullScreenTitle}</div>
                <div className={styles.sysResponseTime_top_img} onClick={() => { onClickFullClose() }}><img src={small} style={{ width: "100%", height: "100%" }} /></div>
            </div>
            {fullScreenType == 'line' ? <Lines data={fullScreenValue} xAxisInterval={0} grid={gridFull} /> : <EchartsBar data={fullScreenValue} grid={gridFull} yAxisPosition={'left'} yAxisAxisLabelFormatter={(value) => {
                return `${value}%`
            }} />}
        </div> :
            <div className={styles.bg}>
                <ComNavBar title={"安全指标"} onBackClick={(e) => {
                    magicStore.triggerMagic('')
                    navigate(routesUrl.home);
                }} />
                <div className={styles.carTabs}>
                    <Tabs value={tab4value} duration={0}  style={{ ...style }} onChange={(value) => {
                        setTab4value(value)
                    }}>
                        {
                            tabTitle.map((item, index) => {
                                return <Tabs.TabPane title={item} key={index}>
                                    {index == 0 && firewall()}
                                    {index == 1 && dyPercep()}
                                    {index == 2 && safetyProtection()}
                                </Tabs.TabPane>
                            })
                        }
                    </Tabs>
                </div>
            </div>}
    </Layout>;

};

export default observer(SystemList);